package com.news.ui;

import com.formdev.flatlaf.FlatLightLaf;
import com.news.model.NewsItem;
import com.news.model.NewsSource;
import com.news.service.NewsService;
import com.news.service.NewsDetailService;
import com.news.service.ContentExtractorService;
import com.news.service.impl.NewsServiceImpl;
import com.news.service.impl.NewsDetailServiceImpl;
import com.news.service.impl.ContentExtractorServiceImpl;
import com.news.model.ArticleContent;
import com.news.model.ArticleImage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.swing.*;
import javax.swing.border.EmptyBorder;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.text.html.HTMLEditorKit;
import javax.swing.text.html.StyleSheet;
import java.awt.*;
import java.awt.datatransfer.StringSelection;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.net.URI;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.ArrayList;

/**
 * 主窗口类
 */
public class MainWindow extends JFrame {
    
    private static final Logger logger = LoggerFactory.getLogger(MainWindow.class);
    
    private final NewsService newsService;
    private final NewsDetailService newsDetailService;
    private final ContentExtractorService contentExtractorService;
    private JList<NewsItem> newsList;
    private DefaultListModel<NewsItem> newsListModel;
    private JEditorPane contentArea; // 改为JEditorPane支持HTML
    private JTextField searchField;
    private JComboBox<NewsSource> sourceComboBox;
    private JButton refreshButton;
    private JButton searchButton;
    private JButton detailButton;
    private JButton extractContentButton; // 新增内容提取按钮
    private JLabel statusLabel;
    
    // 在类的字段声明部分添加
    private JProgressBar progressBar; // 进度条
    private JLabel loadingLabel; // 加载提示标签
    
    public MainWindow() {
        this.newsService = new NewsServiceImpl();
        this.newsDetailService = new NewsDetailServiceImpl();
        this.contentExtractorService = new ContentExtractorServiceImpl();
        
        // 设置现代化外观
        setupLookAndFeel();
        
        // 初始化界面
        initializeUI();
        
        // 设置窗口属性
        setupWindow();
        
        // 加载初始数据
        loadInitialData();
    }
    
    /**
     * 设置现代化外观
     */
    private void setupLookAndFeel() {
        try {
            UIManager.setLookAndFeel(new FlatLightLaf());
        } catch (Exception e) {
            logger.warn("设置外观失败，使用默认外观", e);
        }
    }
    
    /**
     * 初始化用户界面
     */
    private void initializeUI() {
        setLayout(new BorderLayout());
        
        // 创建顶部工具栏
        JPanel topPanel = createTopPanel();
        add(topPanel, BorderLayout.NORTH);
        
        // 创建主体面板
        JSplitPane mainSplitPane = createMainPanel();
        add(mainSplitPane, BorderLayout.CENTER);
        
        // 创建底部状态栏
        JPanel bottomPanel = createBottomPanel();
        add(bottomPanel, BorderLayout.SOUTH);
    }

    /**
     * 创建顶部工具栏
     */
    private JPanel createTopPanel() {
        JPanel panel = new JPanel(new BorderLayout());
        panel.setBorder(new EmptyBorder(10, 10, 10, 10));
        panel.setBackground(Color.WHITE);
        
        // 左侧：标题
        JLabel titleLabel = new JLabel("热门新闻聚合器");
        titleLabel.setFont(new Font("微软雅黑", Font.BOLD, 20));
        titleLabel.setForeground(new Color(51, 51, 51));
        panel.add(titleLabel, BorderLayout.WEST);
        
        // 右侧：控制按钮
        JPanel controlPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
        controlPanel.setBackground(Color.WHITE);
        
        refreshButton = new JButton("刷新");
        refreshButton.setPreferredSize(new Dimension(80, 30));
        refreshButton.setBackground(new Color(0, 123, 255));
        refreshButton.setForeground(Color.WHITE);
        refreshButton.setFocusPainted(false);
        refreshButton.addActionListener(e -> refreshNews());
        
        controlPanel.add(refreshButton);
        panel.add(controlPanel, BorderLayout.EAST);
        
        return panel;
    }
    
    /**
     * 创建主体面板
     */
    private JSplitPane createMainPanel() {
        // 左侧：新闻列表和搜索
        JPanel leftPanel = createLeftPanel();
        
        // 右侧：新闻内容
        JPanel rightPanel = createRightPanel();
        
        JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, leftPanel, rightPanel);
        splitPane.setDividerLocation(400);
        splitPane.setResizeWeight(0.4);
        
        return splitPane;
    }
    
    /**
     * 创建左侧面板（新闻列表）
     */
    private JPanel createLeftPanel() {
        JPanel panel = new JPanel(new BorderLayout());
        panel.setBorder(new EmptyBorder(10, 10, 10, 10));
        
        // 搜索面板
        JPanel searchPanel = createSearchPanel();
        
        // 新闻列表
        newsListModel = new DefaultListModel<>();
        newsList = new JList<>(newsListModel);
        newsList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        newsList.setCellRenderer(new NewsItemRenderer());
        newsList.addListSelectionListener(new NewsListSelectionListener());
        
        JScrollPane listScrollPane = new JScrollPane(newsList);
        listScrollPane.setPreferredSize(new Dimension(380, 400));
        
        panel.add(searchPanel, BorderLayout.NORTH);
        panel.add(listScrollPane, BorderLayout.CENTER);
        
        return panel;
    }
    
    /**
     * 创建搜索面板
     */
    private JPanel createSearchPanel() {
        JPanel panel = new JPanel(new BorderLayout(5, 5));
        panel.setBorder(new EmptyBorder(10, 10, 10, 10));
        panel.setBackground(Color.WHITE);
        
        // 搜索标题
        JLabel searchLabel = new JLabel("🔍 智能搜索");
        searchLabel.setFont(new Font("微软雅黑", Font.BOLD, 14));
        searchLabel.setForeground(new Color(51, 51, 51));
        
        // 搜索输入框
        searchField = new JTextField();
        searchField.setFont(new Font("微软雅黑", Font.PLAIN, 13));
        searchField.setBorder(BorderFactory.createCompoundBorder(
            BorderFactory.createLineBorder(new Color(220, 220, 220)),
            BorderFactory.createEmptyBorder(8, 12, 8, 12)
        ));
        searchField.setPreferredSize(new Dimension(200, 35));
        
        // 添加搜索提示
        searchField.addFocusListener(new java.awt.event.FocusAdapter() {
            @Override
            public void focusGained(java.awt.event.FocusEvent evt) {
                if (searchField.getText().equals("输入关键词搜索新闻...")) {
                    searchField.setText("");
                    searchField.setForeground(Color.BLACK);
                }
            }
            
            @Override
            public void focusLost(java.awt.event.FocusEvent evt) {
                if (searchField.getText().trim().isEmpty()) {
                    searchField.setText("输入关键词搜索新闻...");
                    searchField.setForeground(Color.GRAY);
                }
            }
        });
        
        // 设置初始提示文字
        searchField.setText("输入关键词搜索新闻...");
        searchField.setForeground(Color.GRAY);
        
        // 添加回车搜索功能
        searchField.addActionListener(e -> performSearch());
        
        // 搜索按钮
        searchButton = new JButton("搜索");
        searchButton.setPreferredSize(new Dimension(70, 35));
        searchButton.setBackground(new Color(255, 87, 51)); // 今日头条红色
        searchButton.setForeground(Color.WHITE);
        searchButton.setFont(new Font("微软雅黑", Font.BOLD, 12));
        searchButton.setFocusPainted(false);
        searchButton.setBorder(BorderFactory.createEmptyBorder());
        searchButton.addActionListener(e -> performSearch());
        
        // 热门搜索标签
        JPanel hotSearchPanel = createHotSearchPanel();
        
        // 搜索输入区域
        JPanel inputPanel = new JPanel(new BorderLayout(5, 0));
        inputPanel.add(searchField, BorderLayout.CENTER);
        inputPanel.add(searchButton, BorderLayout.EAST);
        
        // 组装搜索面板
        JPanel topPanel = new JPanel(new BorderLayout());
        topPanel.add(searchLabel, BorderLayout.NORTH);
        topPanel.add(Box.createVerticalStrut(8), BorderLayout.CENTER);
        
        panel.add(topPanel, BorderLayout.NORTH);
        panel.add(inputPanel, BorderLayout.CENTER);
        panel.add(hotSearchPanel, BorderLayout.SOUTH);
        
        return panel;
    }
    
    /**
     * 创建热门搜索面板（类似今日头条的热搜标签）
     */
    private JPanel createHotSearchPanel() {
        JPanel panel = new JPanel(new FlowLayout(FlowLayout.LEFT, 5, 5));
        panel.setBackground(Color.WHITE);
        
        JLabel hotLabel = new JLabel("🔥 热门搜索:");
        hotLabel.setFont(new Font("微软雅黑", Font.PLAIN, 11));
        hotLabel.setForeground(new Color(102, 102, 102));
        panel.add(hotLabel);
        
        String[] hotKeywords = {
            "科技", "财经", "体育", "娱乐", "国际", "教育", "健康", "汽车"
        };
        
        for (String keyword : hotKeywords) {
            JButton hotButton = new JButton(keyword);
            hotButton.setFont(new Font("微软雅黑", Font.PLAIN, 10));
            hotButton.setPreferredSize(new Dimension(50, 20));
            hotButton.setBackground(new Color(248, 248, 248));
            hotButton.setForeground(new Color(51, 51, 51));
            hotButton.setBorder(BorderFactory.createLineBorder(new Color(220, 220, 220)));
            hotButton.setFocusPainted(false);
            hotButton.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
            
            // 添加点击事件
            hotButton.addActionListener(e -> {
                searchField.setText(keyword);
                searchField.setForeground(Color.BLACK);
                performSearch();
            });
            
            // 添加悬停效果
            hotButton.addMouseListener(new java.awt.event.MouseAdapter() {
                @Override
                public void mouseEntered(java.awt.event.MouseEvent evt) {
                    hotButton.setBackground(new Color(255, 87, 51, 20));
                }
                
                @Override
                public void mouseExited(java.awt.event.MouseEvent evt) {
                    hotButton.setBackground(new Color(248, 248, 248));
                }
            });
            
            panel.add(hotButton);
        }
        
        return panel;
    }
    
    /**
     * 创建右侧面板（新闻内容）
     */
    private JPanel createRightPanel() {
        JPanel panel = new JPanel(new BorderLayout());
        panel.setBorder(new EmptyBorder(10, 10, 10, 10));
        
        // 顶部面板：标题和按钮
        JPanel topPanel = new JPanel(new BorderLayout());
        
        // 内容标题
        JLabel contentLabel = new JLabel("新闻详情");
        contentLabel.setFont(new Font("微软雅黑", Font.BOLD, 14));
        contentLabel.setBorder(new EmptyBorder(0, 0, 10, 0));
        
        // 按钮面板
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT, 5, 0));
        
        // 查看详情按钮
        detailButton = new JButton("查看详情");
        detailButton.setPreferredSize(new Dimension(80, 30));
        detailButton.setBackground(new Color(0, 123, 255));
        detailButton.setForeground(Color.WHITE);
        detailButton.setFocusPainted(false);
        detailButton.setEnabled(false);
        detailButton.addActionListener(e -> loadNewsDetail());
        
        // 提取内容按钮
        extractContentButton = new JButton("提取内容");
        extractContentButton.setPreferredSize(new Dimension(80, 30));
        extractContentButton.setBackground(new Color(255, 193, 7));
        extractContentButton.setForeground(Color.BLACK);
        extractContentButton.setFocusPainted(false);
        extractContentButton.setEnabled(false);
        extractContentButton.addActionListener(e -> extractFullContent());
        
        // 访问原文按钮
        openLinkButton = new JButton("访问原文");
        openLinkButton.setPreferredSize(new Dimension(80, 30));
        openLinkButton.setBackground(new Color(40, 167, 69));
        openLinkButton.setForeground(Color.WHITE);
        openLinkButton.setFocusPainted(false);
        openLinkButton.setEnabled(false);
        openLinkButton.addActionListener(e -> openNewsLink());
        
        buttonPanel.add(detailButton);
        buttonPanel.add(extractContentButton);
        buttonPanel.add(openLinkButton);
        
        topPanel.add(contentLabel, BorderLayout.WEST);
        topPanel.add(buttonPanel, BorderLayout.EAST);
        
        // 进度指示面板
        JPanel progressPanel = createProgressPanel();
        
        // 内容区域 - 使用JEditorPane支持HTML
        contentArea = new JEditorPane();
        contentArea.setContentType("text/html");
        contentArea.setEditable(false);
        
        // 设置HTML编辑器样式
        HTMLEditorKit kit = new HTMLEditorKit();
        StyleSheet styleSheet = kit.getStyleSheet();
        styleSheet.addRule("body { font-family: Microsoft YaHei, sans-serif; font-size: 12px; line-height: 1.6; }");
        styleSheet.addRule("h1, h2, h3 { color: #333; margin: 10px 0; }");
        styleSheet.addRule("p { margin: 8px 0; }");
        styleSheet.addRule("img { max-width: 100%; height: auto; margin: 10px 0; }");
        contentArea.setEditorKit(kit);
        
        contentArea.setText("<html><body><div style='text-align: center; color: #666; padding: 50px;'>请选择新闻查看详情...</div></body></html>");
        
        JScrollPane contentScrollPane = new JScrollPane(contentArea);
        contentScrollPane.setPreferredSize(new Dimension(400, 400));
        contentScrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
        
        panel.add(topPanel, BorderLayout.NORTH);
        panel.add(progressPanel, BorderLayout.CENTER);
        panel.add(contentScrollPane, BorderLayout.SOUTH);
        
        // 默认隐藏进度面板
        progressPanel.setVisible(false);
        
        return panel;
    }
    
    /**
     * 创建进度指示面板
     */
    private JPanel createProgressPanel() {
        JPanel panel = new JPanel(new BorderLayout());
        panel.setBorder(new EmptyBorder(10, 10, 10, 10));
        panel.setBackground(Color.WHITE);
        
        // 进度条
        progressBar = new JProgressBar();
        progressBar.setIndeterminate(true);
        progressBar.setStringPainted(true);
        progressBar.setString("正在加载...");
        progressBar.setFont(new Font("微软雅黑", Font.PLAIN, 11));
        
        // 加载提示标签
        loadingLabel = new JLabel("正在提取网页内容，请稍候...", JLabel.CENTER);
        loadingLabel.setFont(new Font("微软雅黑", Font.PLAIN, 12));
        loadingLabel.setForeground(new Color(108, 117, 125));
        loadingLabel.setBorder(new EmptyBorder(10, 0, 0, 0));
        
        // 取消按钮
        JButton cancelButton = new JButton("取消");
        cancelButton.setPreferredSize(new Dimension(60, 25));
        cancelButton.setFont(new Font("微软雅黑", Font.PLAIN, 11));
        cancelButton.addActionListener(e -> hideLoadingIndicator());
        
        JPanel buttonPanel = new JPanel(new FlowLayout());
        buttonPanel.add(cancelButton);
        
        panel.add(progressBar, BorderLayout.NORTH);
        panel.add(loadingLabel, BorderLayout.CENTER);
        panel.add(buttonPanel, BorderLayout.SOUTH);
        
        return panel;
    }
    
    /**
     * 显示加载指示器
     */
    private void showLoadingIndicator(String message) {
        SwingUtilities.invokeLater(() -> {
            loadingLabel.setText(message);
            progressBar.setString("处理中...");
            
            // 获取进度面板
            Component[] components = ((JPanel) getContentPane().getComponent(0))
                .getComponent(1) instanceof JPanel ? 
                ((JPanel) ((JPanel) getContentPane().getComponent(0)).getComponent(1)).getComponents() : new Component[0];
            
            for (Component comp : components) {
                if (comp instanceof JPanel) {
                    JPanel rightPanel = (JPanel) comp;
                    if (rightPanel.getComponentCount() >= 2) {
                        Component progressPanel = rightPanel.getComponent(1);
                        if (progressPanel instanceof JPanel) {
                            progressPanel.setVisible(true);
                            rightPanel.revalidate();
                            rightPanel.repaint();
                            break;
                        }
                    }
                }
            }
        });
    }
    
    /**
     * 隐藏加载指示器
     */
    private void hideLoadingIndicator() {
        SwingUtilities.invokeLater(() -> {
            // 获取进度面板
            Component[] components = ((JPanel) getContentPane().getComponent(0))
                .getComponent(1) instanceof JPanel ? 
                ((JPanel) ((JPanel) getContentPane().getComponent(0)).getComponent(1)).getComponents() : new Component[0];
            
            for (Component comp : components) {
                if (comp instanceof JPanel) {
                    JPanel rightPanel = (JPanel) comp;
                    if (rightPanel.getComponentCount() >= 2) {
                        Component progressPanel = rightPanel.getComponent(1);
                        if (progressPanel instanceof JPanel) {
                            progressPanel.setVisible(false);
                            rightPanel.revalidate();
                            rightPanel.repaint();
                            break;
                        }
                    }
                }
            }
        });
    }
    
    /**
     * 更新加载进度
     */
    private void updateLoadingProgress(String message) {
        SwingUtilities.invokeLater(() -> {
            if (loadingLabel != null) {
                loadingLabel.setText(message);
            }
            if (progressBar != null) {
                progressBar.setString(message);
            }
        });
    }
    
    /**
     * 创建底部状态栏
     */
    private JPanel createBottomPanel() {
        JPanel panel = new JPanel(new BorderLayout());
        panel.setBorder(new EmptyBorder(5, 10, 5, 10));
        panel.setBackground(new Color(248, 249, 250));
        
        statusLabel = new JLabel("就绪");
        statusLabel.setFont(new Font("微软雅黑", Font.PLAIN, 11));
        statusLabel.setForeground(new Color(108, 117, 125));
        
        panel.add(statusLabel, BorderLayout.WEST);
        
        return panel;
    }
    
    /**
     * 设置窗口属性
     */
    private void setupWindow() {
        setTitle("热门新闻聚合器 - v1.0");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(1000, 700);
        setLocationRelativeTo(null);
        
        // 添加窗口关闭监听器
        addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                if (newsService instanceof NewsServiceImpl) {
                    ((NewsServiceImpl) newsService).shutdown();
                }
                System.exit(0);
            }
        });
    }
    
    /**
     * 加载初始数据
     */
    private void loadInitialData() {
        setStatus("正在加载热门新闻...");
        
        CompletableFuture.supplyAsync(() -> {
            return newsService.getAllHotNews(10);
        }).thenAccept(this::updateNewsList)
        .exceptionally(throwable -> {
            logger.error("加载初始数据失败", throwable);
            SwingUtilities.invokeLater(() -> {
                setStatus("加载失败: " + throwable.getMessage());
                JOptionPane.showMessageDialog(this, "加载新闻失败: " + throwable.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
            });
            return null;
        });
    }
    
    /**
     * 刷新新闻
     */
    private void refreshNews() {
        setStatus("正在刷新新闻...");
        refreshButton.setEnabled(false);
        
        CompletableFuture.supplyAsync(() -> {
            newsService.refreshNews();
            return newsService.getAllHotNews(20);
        }).thenAccept(this::updateNewsList)
        .whenComplete((result, throwable) -> {
            SwingUtilities.invokeLater(() -> {
                refreshButton.setEnabled(true);
                if (throwable != null) {
                    logger.error("刷新新闻失败", throwable);
                    setStatus("刷新失败: " + throwable.getMessage());
                } else {
                    setStatus("刷新完成");
                }
            });
        });
    }
    
    /**
     * 执行搜索操作
     */
    private void performSearch() {
        String keyword = searchField.getText().trim();
        if (keyword.isEmpty() || keyword.equals("输入关键词搜索新闻...")) {
            JOptionPane.showMessageDialog(this, "请输入搜索关键词", "搜索提示", JOptionPane.INFORMATION_MESSAGE);
            return;
        }
        
        // 更新搜索按钮状态
        searchButton.setText("搜索中...");
        searchButton.setEnabled(false);
        
        // 在后台执行搜索
        SwingUtilities.invokeLater(() -> {
            try {
                List<NewsItem> searchResults = new ArrayList<>();
                
                                 // 优先搜索今日头条
                 try {
                     List<NewsItem> toutiaoResults = newsService.searchNews(keyword, NewsSource.TOUTIAO, 10);
                     if (toutiaoResults != null && !toutiaoResults.isEmpty()) {
                         searchResults.addAll(toutiaoResults);
                         logger.info("今日头条搜索到 {} 条结果", toutiaoResults.size());
                     }
                 } catch (Exception e) {
                     logger.warn("今日头条搜索失败: {}", e.getMessage());
                 }
                 
                 // 搜索百度新闻
                 try {
                     List<NewsItem> baiduResults = newsService.searchNews(keyword, NewsSource.BAIDU, 8);
                     if (baiduResults != null && !baiduResults.isEmpty()) {
                         searchResults.addAll(baiduResults);
                         logger.info("百度搜索到 {} 条结果", baiduResults.size());
                     }
                 } catch (Exception e) {
                     logger.warn("百度搜索失败: {}", e.getMessage());
                 }
                 
                 // 搜索B站
                 try {
                     List<NewsItem> bilibiliResults = newsService.searchNews(keyword, NewsSource.BILIBILI, 5);
                     if (bilibiliResults != null && !bilibiliResults.isEmpty()) {
                         searchResults.addAll(bilibiliResults);
                         logger.info("B站搜索到 {} 条结果", bilibiliResults.size());
                     }
                 } catch (Exception e) {
                     logger.warn("B站搜索失败: {}", e.getMessage());
                 }
                
                // 在EDT中更新UI
                SwingUtilities.invokeLater(() -> {
                    try {
                        if (searchResults.isEmpty()) {
                            JOptionPane.showMessageDialog(this, 
                                "未找到相关新闻，请尝试其他关键词", 
                                "搜索结果", 
                                JOptionPane.INFORMATION_MESSAGE);
                        } else {
                            // 按热度排序
                            searchResults.sort((a, b) -> Integer.compare(b.getHotScore(), a.getHotScore()));
                            
                            // 更新新闻列表
                            updateNewsList(searchResults);
                            
                                                         // 更新状态栏
                             statusLabel.setText(String.format("搜索完成，找到 %d 条相关新闻", searchResults.size()));
                        }
                    } catch (Exception e) {
                        logger.error("更新搜索结果UI失败", e);
                        JOptionPane.showMessageDialog(this, 
                            "更新搜索结果失败: " + e.getMessage(), 
                            "错误", 
                            JOptionPane.ERROR_MESSAGE);
                    } finally {
                        // 恢复搜索按钮状态
                        searchButton.setText("搜索");
                        searchButton.setEnabled(true);
                    }
                });
                
            } catch (Exception e) {
                logger.error("搜索操作失败", e);
                SwingUtilities.invokeLater(() -> {
                    JOptionPane.showMessageDialog(this, 
                        "搜索失败: " + e.getMessage(), 
                        "搜索错误", 
                        JOptionPane.ERROR_MESSAGE);
                    searchButton.setText("搜索");
                    searchButton.setEnabled(true);
                });
            }
        });
    }
    
    /**
     * 更新新闻列表
     */
    private void updateNewsList(List<NewsItem> newsItems) {
        SwingUtilities.invokeLater(() -> {
            newsListModel.clear();
            for (NewsItem item : newsItems) {
                newsListModel.addElement(item);
            }
            setStatus("已加载 " + newsItems.size() + " 条新闻");
        });
    }
    
    /**
     * 设置状态信息
     */
    private void setStatus(String status) {
        SwingUtilities.invokeLater(() -> {
            statusLabel.setText(status);
        });
    }
    
    /**
     * 新闻列表选择监听器
     */
    private class NewsListSelectionListener implements ListSelectionListener {
        @Override
        public void valueChanged(ListSelectionEvent e) {
            if (!e.getValueIsAdjusting()) {
                NewsItem selectedItem = newsList.getSelectedValue();
                if (selectedItem != null) {
                    displayNewsContent(selectedItem);
                }
            }
        }
    }
    
    // 添加访问原文按钮的成员变量
    private JButton openLinkButton;
    private NewsItem currentNewsItem; // 当前选中的新闻项

    /**
     * 显示新闻内容
     */
    private void displayNewsContent(NewsItem newsItem) {
        this.currentNewsItem = newsItem; // 保存当前新闻项
        
        StringBuilder html = new StringBuilder();
        html.append("<html><body style='font-family: Microsoft YaHei, sans-serif; padding: 15px;'>");
        
        // 新闻来源标签
        html.append("<div style='background: #f8f9fa; padding: 8px; border-radius: 4px; margin-bottom: 15px;'>");
        html.append("<strong style='color: #007bff;'>【").append(newsItem.getSource()).append("】</strong>");
        html.append("</div>");
        
        // 标题
        html.append("<h2 style='color: #333; margin-bottom: 15px; line-height: 1.4;'>")
            .append(newsItem.getTitle()).append("</h2>");
        
        // 元信息
        html.append("<div style='color: #666; font-size: 11px; margin-bottom: 15px; border-bottom: 1px solid #eee; padding-bottom: 10px;'>");
        if (newsItem.getAuthor() != null && !newsItem.getAuthor().trim().isEmpty()) {
            html.append("<span style='margin-right: 15px;'>👤 ").append(newsItem.getAuthor()).append("</span>");
        }
        if (newsItem.getPublishTime() != null) {
            html.append("<span style='margin-right: 15px;'>🕒 ").append(newsItem.getPublishTime()).append("</span>");
        }
        html.append("<span style='margin-right: 15px;'>🔥 热度: ").append(newsItem.getHotScore()).append("</span>");
        html.append("</div>");
        
        // 内容摘要
        String newsContent = newsItem.getContent();
        if (newsContent != null && !newsContent.trim().isEmpty()) {
            html.append("<div style='background: #fff; padding: 15px; border-left: 4px solid #007bff; margin-bottom: 15px;'>");
            html.append("<h4 style='color: #333; margin-bottom: 10px;'>📄 内容摘要</h4>");
            String summary = extractSummary(newsContent);
            html.append("<p style='color: #555; line-height: 1.6;'>").append(summary).append("</p>");
            html.append("</div>");
        } else {
            html.append("<div style='background: #fff3cd; padding: 15px; border-radius: 4px; margin-bottom: 15px;'>");
            html.append("<p style='color: #856404;'>💡 暂无详细内容，点击<strong>\"提取内容\"</strong>获取完整文章内容和图片</p>");
            html.append("</div>");
        }
        
        html.append("</body></html>");
        
        contentArea.setText(html.toString());
        contentArea.setCaretPosition(0);
        
        // 启用相关按钮
        boolean hasUrl = newsItem.getUrl() != null && !newsItem.getUrl().trim().isEmpty();
        detailButton.setEnabled(newsDetailService.isDetailSupported(newsItem));
        extractContentButton.setEnabled(hasUrl && contentExtractorService.isSupported(newsItem.getUrl()));
        openLinkButton.setEnabled(hasUrl);
    }
    
    /**
     * 提取内容摘要
     */
    private String extractSummary(String content) {
        if (content == null || content.trim().isEmpty()) {
            return "暂无内容摘要";
        }
        
        // 清理内容
        String cleaned = content.replaceAll("\\s+", " ").trim();
        
        // 如果内容较短，直接返回
        if (cleaned.length() <= 200) {
            return cleaned;
        }
        
        // 尝试按句号分割，取前几句
        String[] sentences = cleaned.split("。");
        StringBuilder summary = new StringBuilder();
        int charCount = 0;
        
        for (String sentence : sentences) {
            if (charCount + sentence.length() > 180) {
                break;
            }
            if (summary.length() > 0) {
                summary.append("。");
            }
            summary.append(sentence.trim());
            charCount = summary.length();
        }
        
        // 如果摘要太短，按字符截取
        if (summary.length() < 50) {
            return cleaned.substring(0, Math.min(cleaned.length(), 180)) + "...";
        }
        
        return summary.toString() + (summary.toString().endsWith("。") ? "" : "...") ;
    }
    
    /**
     * 打开新闻链接
     */
    private void openNewsLink() {
        if (currentNewsItem == null || currentNewsItem.getUrl() == null) {
            JOptionPane.showMessageDialog(this, "没有可访问的链接", "提示", JOptionPane.INFORMATION_MESSAGE);
            return;
        }
        
        try {
            Desktop.getDesktop().browse(new URI(currentNewsItem.getUrl()));
        } catch (Exception ex) {
            logger.error("打开链接失败", ex);
            JOptionPane.showMessageDialog(this, 
                "无法打开链接: " + ex.getMessage(), 
                "错误", 
                JOptionPane.ERROR_MESSAGE);
        }
    }

    /**
     * 加载新闻详情
     */
    private void loadNewsDetail() {
        NewsItem selectedItem = newsList.getSelectedValue();
        if (selectedItem == null) {
            return;
        }
        
        setStatus("正在加载新闻详情...");
        detailButton.setEnabled(false);
        detailButton.setText("加载中...");
        
        CompletableFuture.supplyAsync(() -> {
            return newsDetailService.getNewsDetail(selectedItem);
        }).thenAccept(detailItem -> {
            SwingUtilities.invokeLater(() -> {
                if (detailItem != null) {
                    displayDetailContent(detailItem);
                    setStatus("详情加载完成");
                } else {
                    setStatus("详情加载失败");
                }
                detailButton.setEnabled(true);
                detailButton.setText("查看详情");
            });
        }).exceptionally(throwable -> {
            SwingUtilities.invokeLater(() -> {
                logger.error("加载新闻详情失败", throwable);
                setStatus("详情加载失败: " + throwable.getMessage());
                detailButton.setEnabled(true);
                detailButton.setText("查看详情");
            });
            return null;
        });
    }
    
    /**
     * 显示详细内容
     */
    private void displayDetailContent(NewsItem detailItem) {
        this.currentNewsItem = detailItem; // 更新当前新闻项
        
        StringBuilder content = new StringBuilder();
        content.append("=== 详细内容 ===\n\n");
        content.append("【").append(detailItem.getSource()).append("】\n\n");
        content.append("标题: ").append(detailItem.getTitle()).append("\n\n");
        
        if (detailItem.getAuthor() != null && !detailItem.getAuthor().trim().isEmpty()) {
            content.append("作者: ").append(detailItem.getAuthor()).append("\n");
        }
        
        if (detailItem.getPublishTime() != null) {
            content.append("发布时间: ").append(detailItem.getPublishTime()).append("\n");
        }
        
        content.append("热度: ").append(detailItem.getHotScore()).append("\n\n");
        
        // 显示详细内容，不显示链接
        String detailContent = detailItem.getContent();
        if (detailContent != null && !detailContent.trim().isEmpty()) {
            content.append("详细内容:\n");
            content.append(detailContent);
        } else {
            content.append("暂无详细内容");
        }
        
        contentArea.setText(content.toString());
        contentArea.setCaretPosition(0);
        
        // 确保访问原文按钮可用
        boolean hasUrl = detailItem.getUrl() != null && !detailItem.getUrl().trim().isEmpty();
        openLinkButton.setEnabled(hasUrl);
    }
    
    /**
     * 提取完整内容
     */
    private void extractFullContent() {
        NewsItem selectedItem = newsList.getSelectedValue();
        if (selectedItem == null) {
            return;
        }
        
        // 显示加载指示器
        showLoadingIndicator("正在连接到网站...");
        setStatus("正在提取完整内容...");
        extractContentButton.setEnabled(false);
        extractContentButton.setText("提取中...");
        
        CompletableFuture.supplyAsync(() -> {
            // 更新进度
            updateLoadingProgress("正在下载网页内容...");
            
            ArticleContent content = contentExtractorService.extractContent(selectedItem);
            
            if (content.isExtractSuccess() && content.hasImages()) {
                // 更新进度
                updateLoadingProgress("正在下载图片 (" + content.getImageCount() + " 张)...");
                
                // 这里可以添加图片缓存逻辑（暂时跳过，因为需要集成ImageCacheService）
                // imageCacheService.cacheImages(content.getImages());
            }
            
            return content;
        }).thenAccept(articleContent -> {
            SwingUtilities.invokeLater(() -> {
                hideLoadingIndicator();
                
                if (articleContent.isExtractSuccess()) {
                    displayExtractedContent(articleContent);
                    setStatus("内容提取成功 - " + articleContent.getContentLength() + " 字，" + 
                             articleContent.getImageCount() + " 张图片");
                } else {
                    setStatus("内容提取失败: " + articleContent.getErrorMessage());
                    showErrorDialog("内容提取失败", articleContent.getErrorMessage());
                }
                extractContentButton.setEnabled(true);
                extractContentButton.setText("提取内容");
            });
        }).exceptionally(throwable -> {
            SwingUtilities.invokeLater(() -> {
                hideLoadingIndicator();
                logger.error("提取完整内容失败", throwable);
                setStatus("内容提取失败: " + throwable.getMessage());
                showErrorDialog("内容提取失败", throwable.getMessage());
                extractContentButton.setEnabled(true);
                extractContentButton.setText("提取内容");
            });
            return null;
        });
    }
    
    /**
     * 显示提取的完整内容
     */
    private void displayExtractedContent(ArticleContent articleContent) {
        StringBuilder html = new StringBuilder();
        html.append("<html><body style='font-family: Microsoft YaHei, sans-serif; padding: 15px; max-width: 100%;'>");
        
        // 状态指示器
        html.append("<div style='background: #d4edda; color: #155724; padding: 10px; border-radius: 4px; margin-bottom: 15px;'>");
        html.append("✅ <strong>完整内容已提取</strong> | ");
        html.append("📝 ").append(articleContent.getContentLength()).append(" 字 | ");
        html.append("🖼️ ").append(articleContent.getImageCount()).append(" 张图片");
        html.append("</div>");
        
        // 标题
        if (articleContent.getTitle() != null) {
            html.append("<h1 style='color: #333; margin-bottom: 20px; line-height: 1.3;'>")
                .append(articleContent.getTitle()).append("</h1>");
        }
        
        // 元信息
        if (articleContent.getAuthor() != null || articleContent.getPublishTime() != null) {
            html.append("<div style='color: #666; font-size: 12px; margin-bottom: 20px; border-bottom: 2px solid #007bff; padding-bottom: 15px;'>");
            if (articleContent.getAuthor() != null) {
                html.append("<span style='margin-right: 20px; background: #f8f9fa; padding: 4px 8px; border-radius: 3px;'>👤 ")
                    .append(articleContent.getAuthor()).append("</span>");
            }
            if (articleContent.getPublishTime() != null) {
                html.append("<span style='background: #f8f9fa; padding: 4px 8px; border-radius: 3px;'>🕒 ")
                    .append(articleContent.getPublishTime()).append("</span>");
            }
            html.append("</div>");
        }
        
        // 主图
        if (articleContent.hasImages()) {
            html.append("<div style='text-align: center; margin: 20px 0;'>");
            html.append("<img src='").append(articleContent.getMainImage().getUrl())
                .append("' style='max-width: 90%; border-radius: 8px; box-shadow: 0 4px 8px rgba(0,0,0,0.1);' alt='")
                .append(articleContent.getMainImage().getAlt() != null ? articleContent.getMainImage().getAlt() : "主图")
                .append("'>");
            if (articleContent.getMainImage().getAlt() != null && !articleContent.getMainImage().getAlt().trim().isEmpty()) {
                html.append("<p style='color: #666; font-size: 11px; margin-top: 5px; font-style: italic;'>")
                    .append(articleContent.getMainImage().getAlt()).append("</p>");
            }
            html.append("</div>");
        }
        
        // 正文内容
        if (articleContent.getContent() != null && !articleContent.getContent().trim().isEmpty()) {
            html.append("<div style='line-height: 1.8; color: #333;'>");
            String[] paragraphs = articleContent.getContent().split("\n\n");
            for (String para : paragraphs) {
                if (!para.trim().isEmpty()) {
                    html.append("<p style='margin: 15px 0; text-indent: 2em;'>").append(para.trim()).append("</p>");
                }
            }
            html.append("</div>");
        }
        
        // 其他图片
        if (articleContent.getImageCount() > 1) {
            html.append("<div style='margin-top: 30px; border-top: 1px solid #eee; padding-top: 20px;'>");
            html.append("<h3 style='color: #333; margin-bottom: 15px;'>📸 相关图片</h3>");
            html.append("<div style='display: flex; flex-wrap: wrap; gap: 10px;'>");
            
            for (int i = 1; i < Math.min(articleContent.getImageCount(), 6); i++) { // 最多显示5张附加图片
                ArticleImage image = articleContent.getImages().get(i);
                html.append("<div style='text-align: center; margin: 10px;'>");
                html.append("<img src='").append(image.getUrl())
                    .append("' style='max-width: 150px; max-height: 150px; border-radius: 4px; box-shadow: 0 2px 4px rgba(0,0,0,0.1);' alt='")
                    .append(image.getAlt() != null ? image.getAlt() : "图片")
                    .append("'>");
                html.append("</div>");
            }
            html.append("</div>");
            html.append("</div>");
        }
        
        html.append("</body></html>");
        
        contentArea.setText(html.toString());
        contentArea.setCaretPosition(0);
        
        // 更新当前新闻项
        this.currentNewsItem.setContent(articleContent.getSummary());
    }
    
    /**
     * 显示错误对话框
     */
    private void showErrorDialog(String title, String message) {
        JOptionPane.showMessageDialog(this, 
            "错误信息：" + message + "\n\n建议：\n- 检查网络连接\n- 确认链接是否有效\n- 稍后重试", 
            title, 
            JOptionPane.ERROR_MESSAGE);
    }
    
    /**
     * 创建右键菜单
     */
    private JPopupMenu createContextMenu(NewsItem newsItem) {
        JPopupMenu menu = new JPopupMenu();
        
        JMenuItem openLinkItem = new JMenuItem("在浏览器中打开");
        openLinkItem.addActionListener(e -> {
            try {
                Desktop.getDesktop().browse(new URI(newsItem.getUrl()));
            } catch (Exception ex) {
                logger.error("打开链接失败", ex);
                JOptionPane.showMessageDialog(this, "无法打开链接: " + ex.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
            }
        });
        
        JMenuItem copyLinkItem = new JMenuItem("复制链接");
        copyLinkItem.addActionListener(e -> {
            try {
                Toolkit.getDefaultToolkit().getSystemClipboard()
                    .setContents(new StringSelection(newsItem.getUrl()), null);
                setStatus("链接已复制到剪贴板");
            } catch (Exception ex) {
                logger.error("复制链接失败", ex);
            }
        });
        
        menu.add(openLinkItem);
        menu.add(copyLinkItem);
        return menu;
    }
    
    /**
     * 新闻源下拉框渲染器
     */
    private static class NewsSourceRenderer extends DefaultListCellRenderer {
        @Override
        public Component getListCellRendererComponent(JList<?> list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
            super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
            
            if (value == null) {
                setText("全部新闻源");
            } else if (value instanceof NewsSource) {
                setText(((NewsSource) value).getDisplayName());
            }
            
            return this;
        }
    }
} 